<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

const store = useStore()
const router = useRouter()

// 获取项目ID
const projectId = computed(() => store.state.projectId)

// 盲测测试数据
const blindTestData = ref({
  result: [],
  count: 0,
  current: 1,
  size: 10
})

// 加载状态
const isLoading = ref(false)

// 查询条件
const queryCondition = reactive({
  name: '',
  method: '',
  url: '',
  status: ''
})

// 测试结果详情
const testResultDetails = ref([])

// 当前测试的接口
const currentTestInterface = ref(null)

// 对话框显示状态
const testDlg = ref(false)
const resultDlg = ref(false)
const compareResultDlg = ref(false)

// 表单校验规则
const rulesBlindTest = reactive({
  expected_result: [{ required: true, message: '请输入预期结果', trigger: 'blur' }]
})

// 测试表单
const testForm = reactive({
  interface_id: '',
  params: {},
  headers: {},
  expected_result: '',
  actual_result: '',
  status: 'pending'
})

// 筛选方法类型列表
const methodOptions = [
  { label: '全部', value: '' },
  { label: 'GET', value: 'GET' },
  { label: 'POST', value: 'POST' },
  { label: 'PUT', value: 'PUT' },
  { label: 'PATCH', value: 'PATCH' },
  { label: 'DELETE', value: 'DELETE' }
]

// 测试状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '待测试', value: 'pending' },
  { label: '通过', value: 'pass' },
  { label: '失败', value: 'fail' }
]

// JSON样例数据
const jsonExample = `{
  "name": "API盲测示例",
  "status": 200,
  "data": {
    "id": 1001,
    "value": "示例值"
  }
}`

// 请求参数示例
const paramsExample = ref({
  query: { page: 1, size: 10 },
  body: { name: "测试数据", value: 123 },
  path: { id: 456 }
})

// 模拟测试数据(用于演示)
const demoInterfaces = [
  {
    id: 1,
    name: '获取用户列表',
    method: 'GET',
    url: '/api/users',
    create_time: new Date().toISOString(),
    status: 'pending',
    expected_result: null,
    actual_result: null
  },
  {
    id: 2,
    name: '创建新用户',
    method: 'POST',
    url: '/api/users',
    create_time: new Date().toISOString(),
    status: 'pass',
    expected_result: '{"code":200,"message":"用户创建成功","data":{"id":1003}}',
    actual_result: '{"code":200,"message":"用户创建成功","data":{"id":1003}}'
  },
  {
    id: 3,
    name: '更新用户信息',
    method: 'PUT',
    url: '/api/users/:id',
    create_time: new Date().toISOString(),
    status: 'fail',
    expected_result: '{"code":200,"message":"更新成功"}',
    actual_result: '{"code":400,"message":"参数错误"}'
  },
  {
    id: 4,
    name: '删除用户',
    method: 'DELETE',
    url: '/api/users/:id',
    create_time: new Date().toISOString(),
    status: 'pending',
    expected_result: null,
    actual_result: null
  },
  {
    id: 5,
    name: '用户登录',
    method: 'POST',
    url: '/api/login',
    create_time: new Date().toISOString(),
    status: 'pass',
    expected_result: '{"code":200,"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."}',
    actual_result: '{"code":200,"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."}'
  }
]

// 加载接口数据
const loadBlindTestData = () => {
  isLoading.value = true

  // 这里模拟API调用，实际项目中应替换为真实的API调用
  setTimeout(() => {
    const filteredData = demoInterfaces.filter(item => {
      const nameMatch = !queryCondition.name || item.name.includes(queryCondition.name)
      const methodMatch = !queryCondition.method || item.method === queryCondition.method
      const urlMatch = !queryCondition.url || item.url.includes(queryCondition.url)
      const statusMatch = !queryCondition.status || item.status === queryCondition.status
      return nameMatch && methodMatch && urlMatch && statusMatch
    })

    blindTestData.value = {
      result: filteredData,
      count: filteredData.length,
      current: 1,
      size: 10
    }
    isLoading.value = false
  }, 500)

  // 实际API调用可以参考下面的注释代码
  /*
  this.$api.getBlindTests(projectId.value, queryCondition).then(res => {
    if (res.status === 200) {
      blindTestData.value = res.data
    }
    isLoading.value = false
  }).catch(err => {
    console.error(err)
    isLoading.value = false
  })
  */
}

// 重置查询条件
const resetForm = () => {
  queryCondition.name = ''
  queryCondition.method = ''
  queryCondition.url = ''
  queryCondition.status = ''
  loadBlindTestData()
}

// 提交查询
const submitForm = () => {
  loadBlindTestData()
}

// 分页大小变化
const sizes = (val) => {
  blindTestData.value.size = val
  loadBlindTestData()
}

// 分页当前页变化
const currentPages = (val) => {
  blindTestData.value.current = val
  loadBlindTestData()
}

// 开始进行API盲测
const startBlindTest = (row) => {
  testDlg.value = true
  currentTestInterface.value = row
  testForm.interface_id = row.id

  // 如果已经有测试结果，则加载之前的结果
  if (row.expected_result) {
    testForm.expected_result = row.expected_result
  } else {
    testForm.expected_result = jsonExample
  }

  // 清空上次的测试结果
  testForm.actual_result = ''
  testForm.status = 'pending'
}

// 执行API测试
const executeTest = () => {
  isLoading.value = true

  // 模拟API调用测试
  setTimeout(() => {
    // 模拟测试结果(50%概率通过，50%概率失败)
    const pass = Math.random() > 0.5

    if (pass) {
      testForm.actual_result = testForm.expected_result
      testForm.status = 'pass'
      ElMessage.success('测试通过')
    } else {
      // 模拟失败结果
      testForm.actual_result = `{
        "code": 400,
        "message": "参数错误",
        "errors": ["参数格式不正确", "缺少必要参数"]
      }`
      testForm.status = 'fail'
      ElMessage.error('测试失败')
    }

    // 更新界面数据
    const index = blindTestData.value.result.findIndex(item => item.id === currentTestInterface.value.id)
    if (index !== -1) {
      blindTestData.value.result[index].expected_result = testForm.expected_result
      blindTestData.value.result[index].actual_result = testForm.actual_result
      blindTestData.value.result[index].status = testForm.status
    }

    isLoading.value = false
    resultDlg.value = true
    testDlg.value = false
  }, 1000)

  // 实际项目中的API调用可参考下面注释代码
  /*
  this.$api.runBlindTest(testForm).then(res => {
    if (res.status === 200) {
      testForm.actual_result = JSON.stringify(res.data.result, null, 2)

      // 比较预期结果和实际结果
      try {
        const expected = JSON.parse(testForm.expected_result)
        const actual = res.data.result

        // 这里可以添加自定义的结果比较逻辑
        const isEqual = JSON.stringify(expected) === JSON.stringify(actual)
        testForm.status = isEqual ? 'pass' : 'fail'

        if (isEqual) {
          ElMessage.success('测试通过')
        } else {
          ElMessage.error('测试失败')
        }
      } catch (e) {
        testForm.status = 'fail'
        ElMessage.error('预期结果格式错误，无法比较')
      }

      // 更新界面数据
      const index = blindTestData.value.result.findIndex(item => item.id === currentTestInterface.value.id)
      if (index !== -1) {
        blindTestData.value.result[index].expected_result = testForm.expected_result
        blindTestData.value.result[index].actual_result = testForm.actual_result
        blindTestData.value.result[index].status = testForm.status
      }

      resultDlg.value = true
      testDlg.value = false
    }
    isLoading.value = false
  }).catch(err => {
    console.error(err)
    testForm.status = 'fail'
    testForm.actual_result = JSON.stringify(err.response.data, null, 2)
    ElMessage.error('测试执行失败')
    isLoading.value = false
    resultDlg.value = true
    testDlg.value = false
  })
  */
}

// 查看测试结果详情
const viewTestResult = (row) => {
  if (!row.actual_result) {
    ElMessage.warning('该接口尚未测试')
    return
  }

  currentTestInterface.value = row
  testForm.expected_result = row.expected_result
  testForm.actual_result = row.actual_result
  resultDlg.value = true
}

// 关闭对话框
const closeDialog = () => {
  testDlg.value = false
  resultDlg.value = false
  compareResultDlg.value = false
}

// 导出测试报告
const exportTestReport = () => {
  ElMessage.success('测试报告导出成功')
}

// 批量测试
const batchTest = () => {
  isLoading.value = true

  setTimeout(() => {
    ElMessage.success('批量测试已完成')
    loadBlindTestData()
    isLoading.value = false
  }, 2000)
}

// 页面加载时获取数据
onMounted(() => {
  loadBlindTestData()
})
</script>

<template>
  <div class="blind-test-container">
    <div class="title">
      <h2>接口盲测</h2>
      <div class="query_model">
        <span>接口名称
          <el-input v-model="queryCondition.name" placeholder="请输入接口名称" autocomplete="off" maxlength="30" :clearable="true" :style="{ width: '200px' }" />
        </span>
        <span>请求类型
          <el-select v-model="queryCondition.method" placeholder="请选择请求类型" :clearable="true" :style="{ width: '200px' }">
            <el-option v-for="item in methodOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </span>
        <span>接口地址
          <el-input v-model="queryCondition.url" placeholder="请输入接口地址" autocomplete="off" maxlength="30" :clearable="true" :style="{ width: '200px' }" />
        </span>
        <span>测试状态
          <el-select v-model="queryCondition.status" placeholder="请选择测试状态" :clearable="true" :style="{ width: '200px' }">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </span>

        <span class="buttons">
          <el-button @click="resetForm" icon="Refresh">重置</el-button>
          <el-button type="success" @click="submitForm" icon="Search">查询</el-button>
        </span>
      </div>

      <div class="operation-buttons">
        <el-button type="primary" @click="batchTest" icon="VideoPlay">批量盲测</el-button>
        <el-button type="success" @click="exportTestReport" icon="DocumentCopy">导出测试报告</el-button>
      </div>

      <!-- 接口列表 -->
      <el-table :data="blindTestData.result" empty-text="暂无数据" v-loading="isLoading" border stripe>
        <el-table-column label="序号" align="center" width="60">
          <template #default="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="接口名称" prop="name" align="center" show-overflow-tooltip />
        <el-table-column label="请求类型" align="center" width="100">
          <template #default="scope">
            <div style="font-weight: bold">
              <span v-if="scope.row.method === 'POST'">
                <el-tag color="#49cc90" size="large">{{ scope.row.method }}</el-tag>
              </span>
              <span v-if="scope.row.method === 'GET'">
                <el-tag color="#61affe" size="large">{{ scope.row.method }}</el-tag>
              </span>
              <span v-if="scope.row.method === 'PUT'">
                <el-tag color="#fca130" size="large">{{ scope.row.method }}</el-tag>
              </span>
              <span v-if="scope.row.method === 'PATCH'">
                <el-tag color="#50e3c2" size="large">{{ scope.row.method }}</el-tag>
              </span>
              <span v-if="scope.row.method === 'DELETE'">
                <el-tag color="#f93e3e" size="large">{{ scope.row.method }}</el-tag>
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="接口地址" prop="url" show-overflow-tooltip align="center" />
        <el-table-column label="测试状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 'pending'" type="info">待测试</el-tag>
            <el-tag v-else-if="scope.row.status === 'pass'" type="success">通过</el-tag>
            <el-tag v-else-if="scope.row.status === 'fail'" type="danger">失败</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center">
          <template #default="scope">
            {{ new Date(scope.row.create_time).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220">
          <template #default="scope">
            <el-button @click="startBlindTest(scope.row)" size="small" type="primary" plain>开始盲测</el-button>
            <el-button @click="viewTestResult(scope.row)" size="small" type="success" plain>查看结果</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-block">
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50, 100]"
          @size-change="sizes" @current-change="currentPages" :total="blindTestData.count"
          :current-page="blindTestData.current" next-text="下一页" prev-text="上一页">
        </el-pagination>
      </div>
    </div>
  </div>

  <!-- 盲测对话框 -->
  <el-dialog v-model="testDlg" title="API盲测" width="60%" :before-close="closeDialog">
    <div v-if="currentTestInterface" class="blind-test-dialog">
      <div class="interface-info">
        <el-descriptions title="接口信息" :column="2" border>
          <el-descriptions-item label="接口名称">{{ currentTestInterface.name }}</el-descriptions-item>
          <el-descriptions-item label="请求方式">
            <el-tag :type="currentTestInterface.method === 'GET' ? 'primary' :
              currentTestInterface.method === 'POST' ? 'success' :
              currentTestInterface.method === 'PUT' ? 'warning' :
              currentTestInterface.method === 'DELETE' ? 'danger' : 'info'">
              {{ currentTestInterface.method }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="接口地址" :span="2">{{ currentTestInterface.url }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="interface-test-form">
        <el-form :model="testForm" :rules="rulesBlindTest" label-position="top">
          <el-tabs type="border-card">
            <el-tab-pane label="请求参数">
              <el-form-item label="请求头">
<!--                <el-input v-model="JSON.stringify(paramsExample.value.query, null, 2)" type="textarea" :rows="5" placeholder="请输入请求头参数（JSON格式）"></el-input>-->
              </el-form-item>

              <el-form-item label="请求体">
<!--                <el-input v-model="JSON.stringify(paramsExample.value.body, null, 2)" type="textarea" :rows="5" placeholder="请输入请求体参数（JSON格式）"></el-input>-->
              </el-form-item>
            </el-tab-pane>

            <el-tab-pane label="预期结果">
              <el-form-item label="预期响应结果" prop="expected_result">
                <el-input v-model="testForm.expected_result" type="textarea" :rows="10" placeholder="请输入预期响应结果（JSON格式）"></el-input>
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="executeTest">执行测试</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 测试结果对话框 -->
  <el-dialog v-model="resultDlg" title="测试结果" width="70%" :before-close="closeDialog">
    <div v-if="currentTestInterface" class="test-result-container">
      <div class="result-header">
        <el-alert :title="testForm.status === 'pass' ? '测试通过' : '测试失败'"
                 :type="testForm.status === 'pass' ? 'success' : 'error'"
                 :closable="false"
                 show-icon />
      </div>

      <div class="result-content">
        <el-tabs type="border-card">
          <el-tab-pane label="结果对比">
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="result-panel">
                  <h3>预期结果</h3>
                  <pre class="json-content">{{ testForm.expected_result }}</pre>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="result-panel">
                  <h3>实际结果</h3>
                  <pre class="json-content" :class="{'error-content': testForm.status === 'fail'}">{{ testForm.actual_result }}</pre>
                </div>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane label="差异分析">
            <div class="diff-analysis">
              <h3>差异分析结果</h3>
              <div v-if="testForm.status === 'pass'">
                <el-empty description="没有发现差异" />
              </div>
              <div v-else>
                <el-alert title="发现差异" type="warning" :closable="false" show-icon />
                <div class="diff-items">
                  <el-table :data="[
                    { key: 'code', expected: '200', actual: '400', status: 'different' },
                    { key: 'message', expected: '成功', actual: '参数错误', status: 'different' },
                    { key: 'data', expected: '对象', actual: '不存在', status: 'missing' }
                  ]" border>
                    <el-table-column label="字段" prop="key" />
                    <el-table-column label="预期值" prop="expected" />
                    <el-table-column label="实际值" prop="actual" />
                    <el-table-column label="状态" prop="status">
                      <template #default="scope">
                        <el-tag v-if="scope.row.status === 'different'" type="danger">不一致</el-tag>
                        <el-tag v-else-if="scope.row.status === 'missing'" type="warning">缺失</el-tag>
                        <el-tag v-else type="success">一致</el-tag>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="测试日志">
            <div class="test-logs">
              <el-timeline>
                <el-timeline-item timestamp="测试开始" placement="top" type="primary">
                  <p>开始执行API盲测</p>
                  <p class="log-time">{{ new Date().toLocaleString() }}</p>
                </el-timeline-item>
                <el-timeline-item timestamp="发送请求" placement="top" type="info">
                  <p>向服务器发送API请求</p>
                  <p>URL: {{ currentTestInterface.url }}</p>
                  <p>Method: {{ currentTestInterface.method }}</p>
                </el-timeline-item>
                <el-timeline-item :timestamp="testForm.status === 'pass' ? '测试通过' : '测试失败'" placement="top"
                                 :type="testForm.status === 'pass' ? 'success' : 'danger'">
                  <p>{{ testForm.status === 'pass' ? '响应结果与预期一致' : '响应结果与预期不一致' }}</p>
                  <p class="log-time">{{ new Date().toLocaleString() }}</p>
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">关闭</el-button>
        <el-button type="primary" @click="startBlindTest(currentTestInterface)">重新测试</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.blind-test-container {
  padding: 16px;
  height: calc(100vh - 65px);
  overflow: auto;
}

.title {
  margin-bottom: 20px;
}

.title h2 {
  margin-bottom: 20px;
  font-weight: 600;
  font-size: 20px;
  color: #303133;
}

.query_model {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 20px;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.query_model > span {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 10px;
}

.operation-buttons {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-end;
}

.buttons {
  margin-left: auto;
}

.pagination-block {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 盲测对话框样式 */
.blind-test-dialog {
  padding: 10px;
}

.interface-info {
  margin-bottom: 20px;
}

.interface-test-form {
  margin-top: 20px;
}

/* 测试结果对话框样式 */
.test-result-container {
  padding: 10px;
}

.result-header {
  margin-bottom: 20px;
}

.result-content {
  margin-top: 20px;
}

.result-panel {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 15px;
  height: 400px;
  overflow: auto;
}

.result-panel h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #606266;
  font-size: 16px;
  font-weight: bold;
}

.json-content {
  white-space: pre-wrap;
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
  background-color: #f9f9f9;
  padding: 10px;
  border-radius: 4px;
  line-height: 1.5;
  overflow: auto;
}

.error-content {
  background-color: #fff5f5;
  border-left: 3px solid #f56c6c;
}

.diff-analysis {
  padding: 10px;
}

.diff-items {
  margin-top: 15px;
}

.test-logs {
  padding: 10px;
}

.log-time {
  color: #909399;
  font-size: 12px;
}

/* 添加响应式设计 */
@media screen and (max-width: 992px) {
  .query_model {
    flex-direction: column;
    align-items: flex-start;
  }

  .query_model > span {
    width: 100%;
    margin-bottom: 10px;
  }

  .buttons {
    margin-left: 0;
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
}
</style>